package com.rednote.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rednote.common.UserContextHolder;
import com.rednote.entity.UserFollow;
import com.rednote.entity.Users;
import com.rednote.entity.vo.FollowUserVO;
import com.rednote.mapper.PostsMapper;
import com.rednote.mapper.UserFollowMapper;
import com.rednote.mapper.UsersMapper;
import com.rednote.service.UserFollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserFollowServiceImpl implements UserFollowService {

    @Autowired
    private UserFollowMapper followMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private PostsMapper postMapper; // 如果关注和帖子相关，没关系可以删掉

    @Override
    public void follow(Integer followedUserId) {
        if (isFollowed(followedUserId)) {
            throw new RuntimeException("已关注该用户");
        } else {
            if(followedUserId.equals(UserContextHolder.getUserId())) {
                throw new RuntimeException("不能关注自己");
            }
            Integer userId = UserContextHolder.getUserId();
            UserFollow follow = new UserFollow();
            follow.setUserId(userId);
            follow.setFollowedUserId(followedUserId);
            followMapper.insert(follow);
            // 如果有关注数统计，比如用户粉丝数，可在这里更新
            // userMapper.updateFollowerCount(followedUserId, 1);
        }
    }

    @Override
    public void unfollow(Integer followedUserId) {
        if (isFollowed(followedUserId)) {
            if(followedUserId.equals(UserContextHolder.getUserId())) {
                throw new RuntimeException("不能取消关注自己");
            }
            Integer userId = UserContextHolder.getUserId();
            QueryWrapper<UserFollow> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId).eq("followed_user_id", followedUserId);
            followMapper.delete(wrapper);
            // 取消关注，更新关注数
            // userMapper.updateFollowerCount(followedUserId, -1);
        } else {
            throw new RuntimeException("未关注该用户");
        }
    }

    @Override
    public boolean isFollowed(Integer followedUserId) {
        Integer userId = UserContextHolder.getUserId();
        QueryWrapper<UserFollow> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("followed_user_id", followedUserId);
        Long count = followMapper.selectCount(wrapper);
        return count != null && count > 0;
    }

    @Override
    public Page<FollowUserVO> listUserFollows(Integer userId, Integer page, Integer size) {
        Page<UserFollow> pageParam = new Page<>(page, size);

        // 查询分页的关注关系
        LambdaQueryWrapper<UserFollow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserFollow::getUserId, userId)
                .orderByDesc(UserFollow::getCreatedAt);

        Page<UserFollow> followPage = followMapper.selectPage(pageParam, queryWrapper);

        // 收集所有被关注用户ID
        List<Integer> followUserIds = followPage.getRecords().stream()
                .map(UserFollow::getFollowedUserId)
                .collect(Collectors.toList());

        if (followUserIds.isEmpty()) {
            return new Page<>(); // 无数据
        }

        // 查询用户基本信息
        List<Users> userList = usersMapper.selectBatchIds(followUserIds);
        Map<Integer, Users> userMap = userList.stream()
                .collect(Collectors.toMap(Users::getUserId, u -> u));

        // 转换为 FollowUserVO
        List<FollowUserVO> voList = followPage.getRecords().stream().map(follow -> {
            Users u = userMap.get(follow.getFollowedUserId());
            FollowUserVO vo = new FollowUserVO();
            if (u != null) {
                vo.setUserId(u.getUserId());
                vo.setUsername(u.getUsername());
                vo.setAvatar(u.getAvatar());
            } else {
                vo.setUserId(follow.getFollowedUserId()); // fallback
                vo.setUsername("未知用户");
            }
            return vo;
        }).collect(Collectors.toList());

        // 构建分页结果
        Page<FollowUserVO> resultPage = new Page<>();
        resultPage.setCurrent(followPage.getCurrent());
        resultPage.setSize(followPage.getSize());
        resultPage.setTotal(followPage.getTotal());
        resultPage.setPages(followPage.getPages());
        resultPage.setRecords(voList);

        return resultPage;
    }

}
